import * as React from 'react';
import {observer} from 'mobx-react';
import {toJS} from 'mobx';
import {Form, Select} from 'antd';
import _ from 'lodash';

const FormItem = Form.Item;
const Option = Select.Option;

interface SelectBean {
    store: any;
    mykey: string;
    title: string;
    labelCol: any;
    wrapperCol: any;
    optionKey?: string;
    optionValue?: string;
    onChange: Function;
    multiple?: boolean;
    optionFilterProp?: string;
    filterOption?: any;
}

@observer
export class SelectItem extends React.Component<SelectBean, any> {
    onChange(me) {
        return function (value) {
            me.props.onChange(value);
        }
    }

    render() {
        const {mykey, title, store, labelCol, wrapperCol, multiple, optionFilterProp = 'value', filterOption = true} = this.props;
        const item = store.fields[mykey];

        const optionKey = this.props.optionKey ? this.props.optionKey : 'id';
        const optionValue = this.props.optionValue ? this.props.optionValue : 'title';

        const className = _.uniqueId(`${mykey}_`);

        const value = _.isArray(toJS(item.value)) ? _.map(toJS(item.value), _.toString) : _.toString(item.value);

        return (
            <FormItem className={className}
                      label={title}
                      labelCol={labelCol}
                      wrapperCol={wrapperCol}
                      hasFeedback={item.hasFeedback}
                      required={item.required}
                      help={item.help}
                      validateStatus={item.validateStatus}>
                <Select
                    optionFilterProp={optionFilterProp}
                    style={{width: '100%'}}
                    value={value}
                    disabled={item.disabled}
                    multiple={multiple}
                    onChange={this.onChange(this)}
                    filterOption={filterOption}
                    getPopupContainer={() => {
                        let element: any = document.querySelector(`.${className}`);
                        return element;
                    }}
                >
                    {item.option.map((itemObj) => {
                        return <Option key={_.toString(itemObj[optionKey])}>{itemObj[optionValue]}</Option>
                    })}
                </Select>
            </FormItem>
        )
    }
}